package behavioral.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: MyCollection
 * @Description: 自定义集合类
 * @Author: liu-hao
 * @Date: 2023-04-10 20:46
 * @Version: 1.0
 **/
public class MyCollection implements Iterable {
    private List<Object> list = new ArrayList<>();

    public void add(Object obj) {
        list.add(obj);
    }

    @Override
    public Iterator iterator() {
        return new MyIterator();
    }

    // 迭代器实现
    private class MyIterator implements Iterator {

        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < list.size();
        }

        @Override
        public Object next() {
            if (hasNext()) {
                return list.get(index++);
            }
            return null;
        }
    }
}
